package cn.apple.imageshow.action;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import cn.apple.imageshow.jpa.JPAUtil;
import cn.apple.imageshow.model.Image;

@SuppressWarnings("serial")
public class ImageShowServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(ImageShowServlet.class
			.getName());
	
	private static final String ATTACHMENT_FILENAME = "filename=";

    private static final String CONTENT_DISPOSITION = "Content-disposition";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		Long id = Long.valueOf(req.getParameter("id"));
		Image image = (Image) JPAUtil.findById(Image.class, id);
		OutputStream output = null;
		try {
			try {
				output = resp.getOutputStream();
			} catch (UnsupportedEncodingException e) {
				log.info(e.getMessage());
			} catch (IOException e) {
				log.info(e.getMessage());
			}
		    byte[] in = image.getBlob().getBytes();
		    int length = in.length;
		    resp.reset();
		    resp.setContentType("image/jpg");
		    resp.setContentLength(length);
            resp.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME+image.getName());
		    int size = 1024;
		    int start = 0;
		    int end = start + size;
		    if ( in != null ){
		        byte[] b = Arrays.copyOfRange(in, start, getEnd(end,length)); 
		        try {
					while(b.length > 0){
						output.write(b);   
				        start = end;
				        end = start + size;
				        b = Arrays.copyOfRange(in, start, getEnd(end,length));
					}
				} catch (IOException e) {
					log.info(e.getMessage());
				}
		    }
		} catch (Exception ex) {
			throw new ServletException(ex);
		}finally{
			output.close();
		}
	}
	
	private int getEnd(int end, int length) {
		return end > length ? length : end;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
